package cn.wolfcode.wolf2w.controller;

import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.RequireLogin;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.wolfcode.wolf2w.service.imp.UserInfoServiceImpl;
import cn.wolfcode.wolf2w.util.JsonResult;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("users")
public class UserInfoControler {
    @Autowired
    private IUserInfoService iUserInfoService;
    @Autowired
    private IUserInfoRedisService iUserInfoRedisService;

    @GetMapping("/get")
    public Object get(String id) {
        return iUserInfoService.get(id);
    }

    @RequireLogin
    @GetMapping("/checkPhone")
    public Object checkPhone(String phone) {
        boolean ret = iUserInfoService.checkPhone(phone);
        return !ret;
    }

    @RequireLogin
    @GetMapping("/sendVerifyCode")
    public Object sendVerifCode(String phone) {
        iUserInfoService.sendVerifyCode(phone);
        return JsonResult.success();
    }

    @RequireLogin
    @PostMapping("/regist")
    public Object regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        try {
            iUserInfoService.register(phone, nickname, password, rpassword, verifyCode);
            //存在问题：异常分两种，1种需要提示用户，2.系统bug不能让用户看到
        } catch (LogicException e) {
            e.printStackTrace();
            return new JsonResult<>(JsonResult.CODE_ERROR_PARAM, e.getMessage(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.defaultError();

        }
        return JsonResult.success();
    }

    @RequireLogin
    @PostMapping("/login")
    public Object login(String username, String password) {
        UserInfo user = iUserInfoService.login(username, password);
        String token = iUserInfoRedisService.setToke(user);
        Map<String, Object> map = new HashMap<>();

        map.put("token", token);
        map.put("user", user);

        return JsonResult.success(map);
    }

    @RequireLogin
    @GetMapping("/currentUser")
    public Object currentUser(HttpServletResponse request) {
        String token = request.getHeader("token");

        UserInfo user = iUserInfoRedisService.getUserByToken(token);
        System.out.println(user);
        return JsonResult.success();

    }



}
